<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 
 * 生成前端登陆用到的config数组	config
 * 后端向前端发送消息	send

*/
namespace core;
defined('BY_JYA') or exit('error');
class jinyun_socket{
	/*
		
	*/
	public function __construct($uniacid=0){
		$this->cloud=core_setting('cloud');
		if($_SESSION['this']=='custom'){
			$this->uniacid=$uniacid?:$_SESSION['uniacid'];
		}else{
			$this->uniacid=$uniacid?:0;
		}
		$this->socket_url='socket.jinyunweb.com';
		$this->socket_port='9998';
	}
	//生成前端连接云平台要用到的config数组
	public function config($uid=0){
		$uid=$uid?:$_SESSION['uid'];
		$uid=$uid?:session_id();//如果尚未登陆，则sessionID作为用户ID
		$config=array(
			'token'=>$this->cloud['cloudkey'],
			'nonce'=>random(32),
			'timestamp'=>TIMESTAMP,
			'uid'=>$uid,
			'uniacid'=>$this->uniacid,
		);
		$config['sign']=get_sign($config,$this->cloud['secret']);
		return $config;
	}
	//后端向前端发送消息接口，向指定用户发送消息
	public function send2uid($message,$uid){
		
		$data=array(
			'token'=>$this->cloud['cloudkey'],
			'nonce'=>random(32),
			'timestamp'=>TIMESTAMP,
			'uid'=>1,
			'to_uid'=>$uid,
			'message'=>$message,
			'uniacid'=>$this->uniacid,
		);
		$data['sign']=get_sign($data,$this->cloud['secret']);
		return $this->send($data);
	}
	//后端向前端发送消息接口，向组发送消息（群发）
	public function send2room($message,$room_id){
		$data=array(
			'token'=>$this->cloud['cloudkey'],
			'nonce'=>random(32),
			'timestamp'=>TIMESTAMP,
			'uid'=>1,
			'to_room'=>$room_id,
			'message'=>$message,
			'uniacid'=>$this->uniacid,
		);
		$data['sign']=get_sign($data,$this->cloud['secret']);
		return $this->send($data);
	}
	private function send($data){
		if(!function_exists('socket_create')){
			exi('socket_create函数被禁用！无法进行socket通信！请连续管理员开启！','error');
		}
		if(!function_exists('socket_set_option')){
			exi('socket_set_option函数被禁用！无法进行socket通信！请连续管理员开启！','error');
		}
		if(!function_exists('socket_connect')){
			exi('socket_connect函数被禁用！无法进行socket通信！请连续管理员开启！','error');
		}
		$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 30, "usec" => 0));
		socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 30, "usec" => 0));
		if(socket_connect($socket,$this->socket_url,$this->socket_port)==false){
			return error('connect fail massege:'.socket_strerror(socket_last_error()));
		}
		$data=ijson_encode($data);
		$data.="\n";
		socket_write($socket, $data, strlen($data));
		$result=socket_read($socket,1024);
		socket_close($socket);
		$result=json_decode(trim($result),true);
		if(!$result){
			return error('数据发送失败！');
		}
		if($result['type']=='error'){
			return error($result['data']);
		}
		return true;
	}
}